package com.example.systema.controller;

import com.example.systema.domain.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/login")
    public String login(User user, Model model, Boolean rememberMe, HttpServletRequest request) {
        //SecurityUtils是用于获取实例化SecurityManager的
        Subject subject = SecurityUtils.getSubject();
        //将前端传递过来的用户信息封装到AuthenticationToken中
        // AuthenticationToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
        //设置rememberMe功能
        if (rememberMe!=null &&rememberMe ==true) {
            token.setRememberMe(true);
        }
        try {
            //认证登录操作,如果没有返回任何异常，表示认证成功，如果返回异常表示登录失败，Shiro对返回的异常进行了定义
            subject.login(token);

            boolean isPermitted = subject.isPermitted("product:add");
            System.out.println(isPermitted);
            boolean hasRole = subject.hasRole("gjyh");
            System.out.println(hasRole);

            User dbUser = (User) subject.getPrincipal(); //获取用户用信息
            /*    request.getSession().setAttribute("userName",dbUser.getUserName());*/
        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "用戶名不存在");
            return "login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("msg", "密碼錯誤");
            return "login";
        }

        return "redirect:/index";
    }

    /**
     * 注销操作
     */
    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout(); //shiro底层将会删除该用户的Session的会话信息
        return "redirect:/toLogin";

    }

}
